package com.feioou.blogdemo;

import com.feioou.blogdemo.config.properties.StorageProperties;
import com.feioou.blogdemo.domain.Receiver;
import com.feioou.blogdemo.service.StorageService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

import java.util.concurrent.CountDownLatch;

/**
 * @description: 启动入口
 * @author: chenyingjie
 * @create: 2019-11-26 14:38
 **/
@SpringBootApplication
@EnableConfigurationProperties(StorageProperties.class)
@EnableWebSecurity
public class BlogDemoApplication {

    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(BlogDemoApplication.class, args);
//        ApplicationContext ctx =  SpringApplication.run(BlogDemoApplication.class, args);

//        StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
//        CountDownLatch latch = ctx.getBean(CountDownLatch.class);
//
//        template.convertAndSend("chat", "Hello from Redis");
//        latch.await();
//
//        System.exit(0);
    }

    @Bean
    CommandLineRunner init(StorageService storageService) {
        return args -> {
            storageService.clear();
            storageService.init();
        };
    }

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter,new PatternTopic("chat"));
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(Receiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

    @Bean
    Receiver receiver(CountDownLatch latch) {
        return  new Receiver(latch);
    }

    @Bean
    CountDownLatch latch() {
        return new CountDownLatch(1);
    }

    @Bean
    StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }


}
